# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Verification(models.Model):
    """设备验证模型"""
    _name = 'device.verification'
    _description = '设备验证管理'
    _order = 'verification_date desc, id desc'
    _rec_name = 'display_name'
    _inherit = ['device.permission.mixin']
    
    # 关联设备
    equipment_id = fields.Many2one('device.equipment', '设备', required=True, ondelete='cascade')
    equipment_name = fields.Char('设备名称', related='equipment_id.name', store=True)
    equipment_code = fields.Char('设备编号', related='equipment_id.code', store=True)
    equipment_category = fields.Char('设备类别', related='equipment_id.category_name', store=True)
    equipment_model = fields.Char('设备型号', related='equipment_id.model', store=True)
    
    # 验证基础信息
    verification_date = fields.Date('验证日期', required=True, default=fields.Date.today)
    verification_cycle = fields.Integer('验证周期（月）', required=True, default=12)
    next_verification_date = fields.Date('下次验证日期', compute='_compute_next_verification_date', store=True)
    internal_code = fields.Char('内部编码', required=True)
    
    # 验证类型
    verification_type = fields.Selection([
        ('initial', '初始验证'),
        ('periodic', '定期验证'),
        ('revalidation', '再验证'),
        ('change', '变更验证')
    ], string='验证类型', default='periodic', required=True)
    
    # 验证状态
    status = fields.Selection([
        ('planned', '计划中'),
        ('ongoing', '进行中'),
        ('passed', '验证通过'),
        ('failed', '验证失败'),
        ('cancelled', '已取消')
    ], string='验证状态', default='planned', required=True)
    
    # 验证标准
    verification_standard = fields.Text('验证标准')
    verification_method = fields.Text('验证方法')
    acceptance_criteria = fields.Text('验收标准')
    
    # 验证结果
    verification_result = fields.Text('验证结果')
    conclusion = fields.Text('验证结论')
    
    # 验证机构
    verification_agency = fields.Char('验证机构')
    verifier = fields.Char('验证员')
    verifier_certificate = fields.Char('验证员证书号')
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.verification')], 
                                   string='验证附件')
    
    # 显示名称
    display_name = fields.Char('显示名称', compute='_compute_display_name', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('verification_date', 'verification_cycle')
    def _compute_next_verification_date(self):
        for record in self:
            if record.verification_date and record.verification_cycle:
                # 计算下次验证日期
                from dateutil.relativedelta import relativedelta
                record.next_verification_date = record.verification_date + relativedelta(months=record.verification_cycle)
            else:
                record.next_verification_date = False
    
    @api.depends('equipment_id', 'verification_date', 'internal_code')
    def _compute_display_name(self):
        for record in self:
            if record.equipment_id and record.verification_date:
                record.display_name = f"{record.equipment_id.name} - {record.internal_code} ({record.verification_date})"
            else:
                record.display_name = "新验证记录"
    
    @api.constrains('verification_cycle')
    def _check_verification_cycle(self):
        for record in self:
            if record.verification_cycle <= 0:
                raise ValidationError('验证周期必须大于0个月。')
    
    @api.constrains('internal_code')
    def _check_internal_code_unique(self):
        for record in self:
            if self.search_count([
                ('internal_code', '=', record.internal_code),
                ('equipment_id', '=', record.equipment_id.id),
                ('id', '!=', record.id)
            ]) > 0:
                raise ValidationError(f'该设备的内部编码 {record.internal_code} 已存在。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_start_verification(self):
        """开始验证"""
        self.write({'status': 'ongoing'})
    
    def action_pass_verification(self):
        """验证通过"""
        self.write({'status': 'passed'})
    
    def action_fail_verification(self):
        """验证失败"""
        self.write({'status': 'failed'})
